package com.bird.pro.wechat;

import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bird.pro.Page;
import com.bird.pro.Params;
import com.bird.pro.annotation.Auth;
import com.bird.pro.cons.Scope;
import com.bird.pro.pojo.BirdPost;
import com.bird.pro.pojo.BirdPosttype;
import com.bird.pro.pojo.BirdUser;
import com.bird.pro.service.IPostService;
import com.bird.pro.service.IPostTypeService;
import com.bird.pro.service.IUserService;
import com.bird.pro.utils.FileUtil;
import com.bird.pro.vo.PostType;

@Controller
@RequestMapping("wechat")
public class WeChatController extends WechatBase {

	private static Logger log = LoggerFactory.getLogger(WeChatController.class);

	@Autowired
	private IUserService userService;
	@Autowired
	private IPostService postService;
	@Autowired
	private IPostTypeService postTypeService;

	@RequestMapping("chat")
	public String wechat() {

		return "auth";
	}

	@RequestMapping("index")
	public String index(HttpSession session, Model model) {
		String openId = "o-MDG1QcHr8ZWmG3s0YexnK4IbfE";
		BirdUser user = getUserInfo(session);
		if (user == null) {
			user = userService.getUserByOpenId(openId);
			setUserInfo(session, user);
		}
		log.info("user:" + user.toString());
		List<BirdPost> posts = postService.queryStickPosts(user.getUserProvince(), user.getUserCity());
		model.addAttribute("posts", posts);
		return "wechat/index";

		// String appid =WechatConfig.appId;
		// String key = WechatConfig.appSecret;
		// String accessToken = "";
		// String openId = "";
		//// String openId = "o-MDG1QcHr8ZWmG3s0YexnK4IbfE";
		// try {
		// Token token = CommonUtil.getToken(appid, key,code);
		// accessToken = token.getAccessToken();
		// openId = token.getOpenId();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// WeixinUserInfo chat = WeChatInfo.getUserInfo(accessToken, openId);
		// if (StringUtils.isNotBlank(openId)) {
		//
		// BirdUser user = userService.getUserByOpenId(openId);
		// if (user == null) {
		// user = new BirdUser();
		// user.setCreateTime(new Date());
		// user.setOpenId(chat.getOpenId());
		// user.setUserName(chat.getNickname());
		// user.setUserProvince(chat.getProvince());
		// user.setUserCity(chat.getCity());
		// user.setUserCounty(chat.getCountry());
		// user.setUserState("1");
		// int result = userService.saveUser(user);
		// if (result > 0) {
		// session.setAttribute("wechatUser", user);
		// } else {
		// return "redirect:/chat";
		// }
		// } else {
		// session.setAttribute("wechatUser", user);
		// }
		// List<BirdPost> posts =
		// postService.queryStickPosts(user.getUserProvince(),user.getUserCity());
		// model.addAttribute("posts", posts);
		// } else {
		// return "redirect:/chat";
		// }
		// return "wechat/index";
	}

	@RequestMapping("post")
	public String post(String type, Model model) {
		PostType postType = postTypeService.getType(type);
		model.addAttribute("type", postType);
		return "wechat/carpool";

	}

	@RequestMapping("list")
	public String post() {
		return "wechat/list";

	}

	@RequestMapping("posts")
	@ResponseBody
	public Page list(Params params, HttpSession session) {

		BirdUser user = (BirdUser) session.getAttribute("wechatUser");
		params.setProvince(user.getUserProvince());
		params.setCity(user.getUserCity());
		
		Page page = postService.queryPostVos(params);
		return page;
	}

	@GetMapping("/publish/{postType}")
	@Auth(scope = Scope.snsapi_userinfo)
	public String publishView(HttpSession session, Model model, @PathVariable String postType) {
		
		model.addAttribute("postType",postTypeService.getTypeByCode(postType));
		// 简历跳转
		if ("job".equals(postType)) {
			return "";
		} else {
			return "wechat/publish";
		}
	}

	@RequestMapping("/publishPostType")
	@Auth(scope = Scope.snsapi_userinfo)
	public String publishPostType(Model model) {
		List<PostType> postTypes = postTypeService.getPostTypes();
		model.addAttribute("types", postTypes);
		return "wechat/publishPostType";
	}

	@PostMapping("/publish")
	@ResponseBody
	public String publish(HttpSession session, @RequestParam("img") MultipartFile img, BirdPost birdPost) {
		System.out.println(session.getServletContext().getRealPath("/"));
		BirdUser user = (BirdUser) session.getAttribute("wechatUser");
		if (img != null && !img.isEmpty()) {
			try {
				String orgName = img.getOriginalFilename();
				String fileName = UUID.randomUUID().toString().replaceAll("-", "") + orgName.substring(orgName.lastIndexOf(".")) ;
				FileUtil.uploadFile(img, "post/", fileName);
				birdPost.setPostImg("post/" + fileName);
			} catch (Exception e) {
				e.printStackTrace(); 
			}
		}
		// to save and save... and saving birdPost....
		birdPost.setUserId(user.getId());
		birdPost.setPostProvince(user.getUserProvince());
		birdPost.setPostCity(user.getUserCity());
		birdPost.setPostCounty(user.getUserCounty());
		birdPost.setPostState("1");
		birdPost.setPostStatus("0");
		postService.savePost(birdPost);
		return "success";
	}
}
